package com.innovation.ic.b1b.framework.util;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

/**
 * xml工具类
 */
public class XmlUtil {

    /**
     * 将Object类型对象转换为xml字符串
     * @param object
     * @return
     */
    public static String objectToXmlString(Object object){
        JSONObject json = JSONObject.fromObject(object);
        XMLSerializer xmlSerializer = new XMLSerializer();
        xmlSerializer.setTypeHintsEnabled(false);
        String value = xmlSerializer.write(json, "UTF-8");
        return value;
    }

    /**
     * 将xml字符串转换为JSON对象
     * @param xmlString
     * @return
     */
    public static JSON xmlStringToJSON(String xmlString){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
                .append("<root>")
                .append(xmlString)
                .append("</root>");
        XMLSerializer xmlSerializer = new XMLSerializer();
        xmlSerializer.setTypeHintsEnabled(false);
        JSON json = xmlSerializer.read(stringBuilder.toString());
        return json;
    }
}
